#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys

usage = """\
Usage:
%s reconstruction_file.h5 (regular expressions accepted)

Command-line tool to convert hdf5-files produced by Python ptycho-package to (binary) Matlab data files.
""" % sys.argv[0]

if len(sys.argv) == 1:
    print usage
    sys.exit(0)

import pyE17.io as pio
import scipy.io as sio

print 'There are %d matching files.' % (len(sys.argv)-1)
for kk in range(1,len(sys.argv)):
   out=pio.h5read(sys.argv[kk])
   print 'Loaded HDF5 file %s' % sys.argv[kk]
   filename_out = sys.argv[kk].replace('.h5','.mat')
   
   # remove some stuff scipy.io.savemat does not understand
   #if out.has_key('datainfo'):
   #  del out['datainfo']
   if out.has_key('history'):
     del out['history']
   #if out.has_key('psize'):
   #  del out['psize']
   
   # values that are no arrays / lists have to be made into one:
   dellist = []
   for k,v in out.iteritems():
     #print k,type(out[k]).__name__    #show all variables present in file
     if type(out[k]).__name__ in ('int', 'float', 'bool'):
       out[k]=[out[k]]
     # mark for removal some stuff scipy.io.savemat does not understand
     elif type(out[k]).__name__ in ('NoneType','dict'):
       dellist.append(k)
     else:
       continue
   
   # remove some stuff scipy.io.savemat does not understand
   for k in dellist:
      del out[k]

   # remove singleton dimensions from probe and object(s)
   if out.has_key('object'):
    out['object']=out['object'].squeeze()
   if out.has_key('obj'):
    out['obj']=out['obj'].squeeze()
   if out.has_key('probe'):
    out['probe']=out['probe'].squeeze()
   
   sio.savemat(filename_out,out)
   print 'Resaved as MAT file %s' % filename_out
sys.exit(0)

   
